package com.sc.pattern.worker;

import java.util.Arrays;

/**
 * Created  on 2018/1/13.
 *
 * @author sc
 */
public class Channel {
    private final static int MAX_REQUEST = 100;
    private Request[] requestQ;
    private int head;
    private int tail;
    private int count;
    private final WorkThread[] workPool;

    public Channel(int workers) {
        this.requestQ =  new Request[MAX_REQUEST];
        this.head = 0;
        this.tail = 0;
        this.count = 0;
        this.workPool = new WorkThread[workers];
        this.init();
    }
    private void init(){
        for (int i = 0; i < workPool.length; i++) {
            workPool[i] = new WorkThread("Worker-"+i,this);
        }
    }
    /**
     *start worker
    */
    public void startWorker(){
        Arrays.asList(workPool).forEach(WorkThread::start);
    }
    public synchronized void put(Request request){
        while (count>=requestQ.length){
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        this.requestQ[tail] = request;
        this.tail = (tail+1)%requestQ.length;
        count++;
        this.notifyAll();
    }

    public synchronized Request take() throws InterruptedException {
        while (count<=0){
            this.wait();
        }
        Request request = this.requestQ[head];
        this.head  =(head+1)%requestQ.length;
        this.count--;
        this.notifyAll();
        return request;
    }
}
